$(document).ready(function () {
    var form = $('#form');
    var name = $('#name');
    var shortName = $('#short-name');
    var branchesInputType = $('#branches-input-type');
    var branchesSelect = $('#branches-select');
    var urlFromSelect = $('#url-from-select');
    var urlToSelect = $('#url-to-select');
    var branchesInput = $('#branches-input');
    var urlFromInput = $('#url-from-input');
    var urlToInput = $('#url-to-input');
    var interval = $('#interval');
    var refreshButton = $('#refresh-branches-button');
    var indicator = $('#indicator');
    var submitButton = $('button[type=submit]');

    var askUserModal = $('#ask-user-modal');
    var addTaskButton = $('#add-task-button');
    var modalDismissButton = $('#modal-dismiss-button');

    var projectShortName = $('#project-short-name');
    var taskShortName = $('#task-short-name');

    urlFromSelect.change(function () {
        urlFromInput.val($(this).val());
    });
    urlFromSelect.change();

    urlToSelect.change(function () {
        urlToInput.val($(this).val());
    });
    urlToSelect.change();

    name.focusin(function () {
        if (name.isBlank()) {
            if (branchesInputType.val() == 'select' && !urlFromSelect.isBlank() && !urlToSelect.isBlank()) {
                name.val(urlFromSelect.getLastUrlToken() + ' >> ' + urlToSelect.getLastUrlToken());
                if (name.valid() && shortName.isBlank()) {
                    setShortNameFromName();
                }
            } else if (formValidator.check(urlFromInput) && formValidator.check(urlToInput)) {
                name.val(urlFromInput.getLastUrlToken() + ' >> ' + urlToInput.getLastUrlToken());
                if (name.valid() && shortName.isBlank()) {
                    setShortNameFromName();
                }
            }
        }
    });

    refreshButton.click(function () {
        refreshButton.disable();
        branchesInputType.disable();
        urlFromSelect.disable();
        urlToSelect.disable();
        urlFromInput.disable();
        urlToInput.disable();
        submitButton.disable();
        indicator.show();

        $.ajax({
            url: _context + projectShortName.val() + "?refresh-branches",
            method: 'post',
            dataType: 'json',
            success: function (branches) {
                replaceBranches(urlFromSelect, branches);
                replaceBranches(urlToSelect, branches);

                indicator.hide();
                refreshButton.enable();
                branchesInputType.enable();
                urlFromSelect.enable();
                urlToSelect.enable();
                urlFromInput.enable();
                urlToInput.enable();
                submitButton.enable();

                popNotification({
                    type: 'success',
                    title: 'Refresh branches',
                    text: '<b>' + branches.length + '</b> branches were detected'
                });
            }
        });
    });

    var formValidator = form.validate({
        onkeyup: validator,
        onfocusout: validator,
        rules: {
            name: {
                required: true,
                maxlength: 64
            },
            shortName: {
                required: true,
                maxlength: 32,
                pattern: shortNamePattern
            },
            interval: {
                required: true,
                min: 5
            }
        },
        unhighlight: function (element) {
            if (['branchesInputType', 'urlFromSelect', 'urlToSelect'].indexOf(element.name) < 0) {
                unhighlighter(element);
            }
        },
        submitHandler: function () {
            $.ajax(taskShortName.length > 0 ? getEditTaskSubmitter() : getCreateTaskSubmitter());
        }
    });

    addTaskButton.click(function () {
        window.location.reload();
    });

    var nameRemoteValidationRule = {remote: _context + projectShortName.val() + '?is-name-available'};

    name.focusout(function () {
        if (shortName.isBlank() && formValidator.check(name)) {
            setShortNameFromName();
        }

        if (!name.isInitialValueSet()) {
            name.rules('add', nameRemoteValidationRule);
        }
    });
    name.focusin(function () {
        name.rules('remove', 'remote');
    });

    var shortNameRemoteValidationRule = {remote: _context + projectShortName.val() + '?is-short-name-available'};
    shortName.focusout(function () {
        if (!shortName.isInitialValueSet()) {
            shortName.rules('add', shortNameRemoteValidationRule);
        }
    });
    shortName.focusin(function () {
        shortName.rules('remove', 'remote');
    });

    branchesInputType.change(function () {
        if (branchesInputType.val() == 'select') {
            urlInputRules(urlFromInput, 'remove');
            urlInputRules(urlToInput, 'remove');

            branchesInput.hide();
            branchesSelect.show();
            refreshButton.show();
        } else {
            urlInputRules(urlFromInput, 'add');
            urlInputRules(urlToInput, 'add');

            refreshButton.hide();
            branchesSelect.hide();
            branchesInput.show();

            urlFromInput.valid();
            urlToInput.valid();
        }
    });
    branchesInputType.change();

    function getCreateTaskSubmitter() {
        return {
            url: _context + projectShortName.val() + "?create",
            async: false,
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: getTaskData(),
            success: function (response) {
                if (response.valid) {
                    modalDismissButton.click(function () {
                        window.location.href = _context + projectShortName.val() + "/" + response.data;
                    });
                    askUserModal.modal();
                } else {
                    handleViolations(response);
                }
            },
            error: function () {
                alert('Task was not saved due to internal error');
            }
        }
    }

    function getEditTaskSubmitter() {
        return {
            url: _context + projectShortName.val() + '/' + taskShortName.val() + "?apply",
            async: false,
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: getTaskData(),
            success: function (response) {
                if (response.valid) {
                    window.location.href = _context + projectShortName.val() + "/" + response.data;
                } else {
                    handleViolations(response);
                }
            },
            error: function () {
                alert('Task was not saved due to internal error');
            }
        }
    }

    function getTaskData() {
        return JSON.stringify({
            name: name.val(),
            shortName: shortName.val(),
            urlFrom: getUrlFrom(),
            urlTo: getUrlTo(),
            executionInterval: interval.val() * 60
        });
    }

    function urlInputRules(input, action) {
        input.rules(action, 'svnUrl');
        input.rules(action, 'required');
    }

    function replaceBranches(select, branches) {
        var selected = select.val();
        select.empty();
        if (branches.length > 0) {
            $.each(branches, function () {
                var option = $('<option></option>').attr('value', this.url).text(this.name);
                if (this.url == selected) {
                    option.attr('selected', 'selected');
                }
                select.append(option);
            });
        } else {
            select.append($('<option disabled="disabled">No branches</option>'));
        }
    }

    function getUrlFrom() {
        if (branchesInputType.val() == 'select') {
            return urlFromSelect.val();
        } else {
            return urlFromInput.val();
        }
    }

    function getUrlTo() {
        if (branchesInputType.val() == 'select') {
            return urlToSelect.val();
        } else {
            return urlToInput.val();
        }
    }

    function setShortNameFromName() {
        shortName.val(name.val()
            .replace(preReplaceRegExp, '__')
            .replace(replaceRegExp, '_'));
        shortName.valid();
    }
});
